import { ReactElement, useRef, useEffect, useContext } from 'react'
import { Modal, Form, FormInstance, Input, Row, Col } from 'antd'
import { Context } from '../../../../context'
import style from './index.module.less'

const { Item, List } = Form

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props): ReactElement {
  const { updateCaseDetail, caseDetail } = useContext(Context)
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {

  }, [])
  useEffect(() => {
    const c = formRef.current
    if (visible && caseDetail !== null && c !== null) {
      const list = typeof caseDetail.applicant_name === 'string' ? caseDetail.applicant_name.split(',').filter(li => li.length > 0) : [undefined]
      c.setFieldsValue({ applicant_name: list })
    } else if (!visible && c !== null) {
      c.resetFields()
    }
  }, [caseDetail, formRef, visible])
  return (
    <Modal title='修改申请人' visible={visible} onOk={() => formRef.current?.submit()} onCancel={hide} maskClosable>
      <Form ref={formRef} initialValues={{ applications: [] }} labelCol={{ flex: '80px' }} onFinish={d => updateCaseDetail({ applicant_name: d.applicant_name.join() })}>
        <List name='applicant_name'>
          {(fields, { add, remove }, { errors }) => (
            <>
              {
                fields.map((field, index) => {
                  return (
                    <Row key={field.key}>
                      <Col flex='auto'>
                        <Item label={`申请人${index + 1}`} {...field} rules={[{ required: true, message: '申请人不能为空' }]}>
                          <Input placeholder='请输入' />
                        </Item>
                      </Col>
                      <Col flex='80px'>
                      {
                        index === fields.length - 1
                          ? (
                          <div className={style['btn-block']} onClick={() => add()}>
                            <button className={style.btn} type='button'>+</button>
                          </div>
                            )
                          : (
                          <div className={style['btn-block']} onClick={() => remove(field.name)}>
                            <button className={style.btn} type='button'>-</button>
                          </div>
                            )
                      }
                      </Col>
                    </Row>
                  )
                })
              }
            </>
          )}
        </List>
      </Form>
    </Modal>
  )
}

export default Main
